package org.mili.ticketeer.dao;

import org.mili.application.dao.AbstractDao;
import org.mili.application.dao.DaoException;
import org.mili.application.dao.MofificationType;
import org.mili.application.dao.RowTransformer;
import org.mili.application.dao.query.QueryBuilder;
import org.mili.ticketeer.dto.Action;
import org.mili.ticketeer.dto.Contact;
import org.mili.ticketeer.dto.ContactAction;
import org.mili.application.dto.Identifieable;
import org.mili.application.util.Lambda;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class ContactActionDao extends AbstractDao {

    public ContactActionDao() {
        super(ContactAction.UniqueFields.values(), ContactAction.Fields.values(), ContactAction.TABLE);
    }

    public Boolean assign(final Contact contact, final Action action) throws DaoException {
        return doInDao(new Lambda<Boolean>() {
            @Override
            public Boolean exec(Object... params) throws SQLException, DaoException {
                ContactAction contactAction = new ContactAction();
                contactAction.setAction(action.getId());
                contactAction.setContact(contact.getId());
                boolean result = update("insert into `contact_action` (`contact`, `action`) values(?, ?);",
                        contact.getId(), action.getId()) == 1;
                boolean archive = archive(contactAction, MofificationType.CREATE) == 1;
                return result && archive;
            }
        });
    }

    public List<Contact> getAssignmentsFor(final Action action) throws DaoException {
        final List<Integer> contacts = read(
                new RowTransformer() {
                    @Override
                    public Integer transform(ResultSet resultSet) throws SQLException {
                        return resultSet.getInt(ContactAction.Fields.CONTACT.name());
                    }
                },
                QueryBuilder.createQueryBuilder()
                    .select()
                    .fields(fields)
                    .from(table)
                    .where()
                    .eq(ContactAction.Fields.ACTION, action.getId())
                    .build()
        );

        if (contacts.size() == 0) {
            return Collections.emptyList();
        }

        return read(new ContactDao.ContactRowTransformer(),
                    QueryBuilder.createQueryBuilder()
                        .select()
                        .fields(Identifieable.Fields.ID, Contact.Fields.values())
                        .from(Contact.TABLE)
                        .where()
                        .in(Identifieable.Fields.ID, contacts)
                        .build()
        );
    }
}
